#!/usr/bin/env python
# -*- coding:utf-8 -*-

# import
import sys
import hashlib

# common
from common.log import log
from common.db.db import Db
from common.const import Const
from common.util import Util

defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
    reload(sys)
    sys.setdefaultencoding(defaultencoding)


class User:
    '''用户管理'''

    def __init__(self):
        pass

    def login(self, username, passwd):
        '''登录，返回token'''
        log.debug('login, username:%s, passwd:%s' % (username, passwd))

        ret_code = 1004
        ret_data = '{"info": "user is not exists or password is incorrect."}'

        # 查询密码并比对
        sql = ('select PASSWD from T_USER where USERNAME="%s";' % (username))
        log.debug('query user passwd, sql:%s' % (sql))
        sql_ret = Db.execute(sql)
        if len(sql_ret) > 0:
            # 既存密码
            passwd_db = str(sql_ret[0][0])
            # 请求密码
            passwd_request = hashlib.md5(passwd).hexdigest()
            if passwd_request == passwd_db:
                # 密码正确，返回token
                token = Util.generate_token()
                ret_code = 1000
                ret_data = '{"token":"%s"}' % token

        return ret_code, ret_data

    def add_user(self, username, nickname, passwd, phone, email):
        '''增加用户'''
        log.debug('add_user:%s,%s,%s,%s,%s' %
                  (username, nickname, passwd, phone, email))

        ret_code = 1000
        ret_data = None

        sql = 'select * from T_USER where USERNAME="%s";' % (username)
        sql_ret = Db.execute(sql)
        if len(sql_ret) > 0:
            # 已经存在该用户
            ret_code = 1006
            ret_data = '{"info": "user is repeat."}'
        else:
            # 不存在该用户，将新建
            passwd_encode = hashlib.md5(passwd).hexdigest()
            sql = ('insert into T_USER values '
                   '("%s","%s","%s","%s","%s","","");') % (
                username, nickname, passwd_encode, phone, email)
            log.debug('insert user, sql:%s' % (sql))
            Db.execute(sql)

        return ret_code, ret_data

    def query_users(self):
        '''查询用户信息'''
        log.debug('query_users')

        ret_code = 1000
        ret_data = '[]'

        sql = 'select USERNAME,NICKNAME,PHONE,EMAIL from T_USER'
        log.debug('query_users, sql:%s' % (sql))

        sql_ret = Db.execute(sql)
        if len(sql_ret) > 0:
            # 组织数据结构
            ret_data = '['
            for i in range(0, len(sql_ret)):
                tmp_username = str(sql_ret[i][0])
                tmp_nickname = str(sql_ret[i][1])
                tmp_phone = str(sql_ret[i][2])
                tmp_email = str(sql_ret[i][3])

                ret_data += '{"username":"' + tmp_username
                ret_data += '","nickname":"' + tmp_nickname
                ret_data += '","phone":"' + tmp_phone
                ret_data += '","email":"' + tmp_email + '"},'
            ret_data = ret_data[:-1] + ']'

        return ret_code, ret_data

    def delete_user(self, username):
        '''删除用户'''
        log.debug('delete_user, username:%s' % (username))

        ret_code = 1000
        ret_data = None

        sql = 'delete from T_USER where USERNAME="%s";' % (username)
        Db.execute(sql)

        return ret_code, ret_data

    def modify_password(self, username, old_passwd, new_passwd):
        '''修改密码'''
        log.debug('modify_password, username:%s, old_passwd:%s, '
                  'new_passwd:%s' % (
                      username, old_passwd, new_passwd))

        ret_code = 1001
        ret_data = '{"info": "Invalid account or password."}'

        sql = 'select PASSWD from T_USER where USERNAME="%s";' % (username)
        sql_ret = Db.execute(sql)

        if len(sql_ret) > 0:
            # 既存密码
            passwd_db = str(sql_ret[0][0])
            # 请求密码
            old_passwd_request = hashlib.md5(old_passwd).hexdigest()
            if old_passwd_request == passwd_db:
                # 密码正确，更新新密码
                new_passwd_request = hashlib.md5(new_passwd).hexdigest()
                sql = 'update T_USER set PASSWD="%s" where USERNAME="%s";' % (
                    new_passwd_request, username)
                Db.execute(sql)

                ret_code = 1000
                ret_data = None

        return ret_code, ret_data
